//1. 使用自定义hook，实现N秒倒计时，初始显示 N (来自props)，每秒递减1，到0时停止倒计时，并显示 “活动开始”
import React, { useState, useEffect, useRef } from 'react';

// TODO: 填写useCountDown

export function useCountDown(n) {
  const [count, setCount] = useState(n);

  let timer = useRef(null);
  useEffect(() => {
    timer.current = setInterval(() => {
      setCount(count - 1);
    }, 1000);
    return () => {
      clearInterval(timer.current);
    };
  }, [count]);
  useEffect(() => {
    if (count === 0) {
      clearInterval(timer.current);
    }
  }, [count]);
  return count;
}

function Timer() {
  const time = useCountDown(6);

  return <span>{time === 0 ? '活动开始' : `剩余${time}秒`}</span>;
}

export default Timer;
